<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['goodsLend:add'])" type="primary"
            @click="handleAddGoodsLend">新增</el-button>
          <el-button type="success" size="mini" v-if="checkPermission(['goodsLend:confirm'])" @click="handleConfirmGoodsLend"
            :disabled="multipleSelection.length === 0">确认</el-button>
          <el-button size="mini" v-if="checkPermission(['goodsLend:del'])" @click="handleDeleteGoodsLend()" type="danger"
            :disabled="multipleSelection.length === 0">删除</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入借出单编号" advanced
            advancedWidth="465">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="所属部门">
                  <el-cascader v-model="advancedForm.dept_id" :options="deptList" :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true
                  }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="advancedForm.status">
                    <el-option key="NEW" label="新创建" value="NEW" />
                    <el-option key="CONFIRMED" label="已确认" value="CONFIRMED" />
                    <el-option key="RETURNED" label="已归还" value="RETURNED" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.goodsLend_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="false" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="借出单编号">
          <template slot-scope="scope">
            <router-link
              v-if="checkPermission(['goodsLend'])"
              style="color: #409eff;"
              :to="{ name: 'goodsLendDetail', params: { id: scope.row.id } }">
              {{ scope.row.sn }}
            </router-link>
            <span v-else>{{scope.row.sn}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lend_time" label="调整时间">
          <template slot-scope="scope">{{ scope.row.lend_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="dept_name" label="所属部门" />
        <el-table-column prop="warehouse_name" label="仓库" />
        <el-table-column prop="lend_desc" label="借出说明" />
        <el-table-column prop="lend_person" label="借出人" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="success" size="mini"
              v-if="scope.row.status === 'CONFIRMED' && checkPermission(['goodsLend:return'])"
              @click="handleReturnGoodsLend(scope.row)">归还</el-button>
            <el-button size="mini" v-if="scope.row.status === 'NEW' && checkPermission(['goodsLend:edit'])"
              @click="handleEditGoodsLend(scope.row)">编辑</el-button>
            <el-button type="primary" v-if="checkPermission(['goodsLend:print'])" size="mini"
              @click="handlePrintGoodsLendDialog(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>

    <el-dialog title="调整单表" :visible.sync="dialogVisible" width="940px" center>
      <el-button size="mini" type="primary" @click="handlePrintGoodsLend" class="print">打印</el-button>
      <div id="deliverySheet" style="width:900px">
        <div class="tips-t">
          <div>
            借出单号:{{ goodsLendForm.sn }}
          </div>
          <div>
            借出时间:{{ goodsLendForm.lend_time | unixToDateStr }}
          </div>
          <div>
            仓库:{{ goodsLendForm.warehouse_name }}
          </div>
        </div>
        <div class="tips-t">
          <div>
            所属部门:{{ goodsLendForm.dept_name }}
          </div>
          <div>
            出借人:{{ goodsLendForm.lend_person }}
          </div>
          <div>
            经手人:{{ goodsLendForm.lend_register }}
          </div>
        </div>
        <div class="tips-t">
          <div>
            借出说明:{{ goodsLendForm.lend_desc }}
          </div>
          <div></div>
          <div></div>
        </div>
        <el-table :data="goodsLendForm.product_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }" style=" width:100%;margin-top: 20px;">
          <el-table-column label="批次编号" width="179">
            <template slot-scope="scope">
              {{ scope.row.stock_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号" width="170">
            <template slot-scope="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="170">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="110">
            <template slot-scope="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="单位" width="50">
            <template slot-scope="scope">
              {{ scope.row.unit }}
            </template>
          </el-table-column>
          <el-table-column label="库存数量" width="110">
            <template slot-scope="scope">
              {{ scope.row.stock_num }}
            </template>
          </el-table-column>
          <el-table-column label="借出数量" width="110">
            <template slot-scope="scope">
              {{ scope.row.lend_num }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_GoodsLend from '@/api/goodsLend'
import Print from 'print-js'
import * as API_Setting from '@/api/setting'
import { Foundation } from '~/ui-utils'
export default {
  name: 'goodsLend',
  data() {
    return {
      deptList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      dialogVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      goodsLendForm: {}
    }
  },
  mounted() {
    this.GET_GoodsLendList()
    this.GET_DeptList()
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (newVal.query.status) {
          this.params.status = newVal.query.status
          this.advancedForm.status = newVal.query.status
        }
        this.params.page_no = 1
        this.GET_GoodsLendList()
      }
    }
  },
  methods: {
    handleEditGoodsLend(row) {
      this.$router.push({
        name: 'goodsLendEdit',
        params: { id: row.id }
      })
    },
    handleReturnGoodsLend(row) {
      this.$router.push({
        name: 'goodsLendReturn',
        params: { id: row.id }
      })
    },
    /** 状态 */
    statusFilter(val) {
      switch (val) {
        case 'NEW':
          return '新创建'
        case 'CONFIRMED':
          return '已确认'
        case 'RETURNED':
          return '已归还'
        default:
          return ''
      }
    },
    handleConfirmGoodsLend() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_GoodsLend.lendFormConfirm(ids).then(() => {
          this.$message.success('确认成功！')
          this.GET_GoodsLendList()
        })
      }).catch(() => { })
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 打印对账详情 */
    handlePrintGoodsLend() {
      Print({
        printable: 'deliverySheet',
        type: 'html',
        targetStyles: ['*'],
        ignoreElements: ['no-logs', 'goods-image', 'no-btn']
      })
    },
    handleDeleteGoodsLend() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要删除这些借出单吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_GoodsLend.deleteGoodsLend(ids).then(() => {
          this.$message.success('删除成功！')
          this.GET_GoodsLendList()
        })
      }).catch(() => { })
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_GoodsLendList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_GoodsLendList()
    },

    /** 添加调整单 */
    handleAddGoodsLend() {
      this.$router.push({
        name: 'goodsLendAdd',
        params: { callback: this.GET_GoodsLendList }
      })
    },
    /** 打印调整单 */
    handlePrintGoodsLendDialog(row) {
      this.GET_GoodsLendDetail(row.id)
    },
    /** 获取调整单详情页面数据 */
    GET_GoodsLendDetail(id) {
      API_GoodsLend.getGoodsLendInfo(id).then(response => {
        this.goodsLendForm = response
        if (response.product_list && response.product_list.length) {
          var str = ''
          response.product_list.forEach(function(i) {
            str += i.product_name + '、'
          })
        }
        this.goodsLendForm.illustrate = str
        this.dialogVisible = true
      })
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_GoodsLendList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.goodsLend_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.goodsLend_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.goodsLend_time_range[1]) / 1000)
      }
      delete this.params.goodsLend_time_range
      this.params.page_no = 1
      this.GET_GoodsLendList()
    },
    /** 获取调整单列表 */
    GET_GoodsLendList() {
      this.loading = true
      API_GoodsLend.getGoodsLendList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 790px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: left;
    padding-left: 70px;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
